package com.sh.rbac.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sh.rbac.core.common.exception.CustomException;
import com.sh.rbac.core.mybatis.annotation.DataPermission;
import com.sh.rbac.core.common.result.ResultCodeEnum;
import com.sh.rbac.domain.converter.DeptConverter;
import com.sh.rbac.domain.dto.dept.DeptQueryDTO;
import com.sh.rbac.domain.dto.dept.DeptSaveDTO;
import com.sh.rbac.domain.dto.dept.DeptUpdateDTO;
import com.sh.rbac.domain.entity.Dept;
import com.sh.rbac.domain.vo.dept.DeptVO;
import com.sh.rbac.mapper.DeptMapper;
import com.sh.rbac.service.DeptService;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author lucky
 * @description 针对表【sys_dept(系统部门)】的数据库操作Service实现
 * @createDate 2025-05-19 18:38:06
 */
@Service
public class DeptServiceImpl extends ServiceImpl<DeptMapper, Dept>
        implements DeptService {

    @Override
    public Boolean save(DeptSaveDTO deptSaveDTO) {
        Dept dept = DeptConverter.INSTANCE.toEntity(deptSaveDTO);
        return super.save(dept);
    }

    @Override
    public Boolean updateById(DeptUpdateDTO deptUpdateDTO) {
        Dept dept = DeptConverter.INSTANCE.toEntity(deptUpdateDTO);
        return super.updateById(dept);
    }

    @Override
    public Boolean updateStatus(Long id, Integer status) {
        Dept dept = new Dept();
        dept.setId(id);
        dept.setStatus(status);

        return super.updateById(dept);
    }

    @Override
    public DeptVO getById(Long deptId) {
        return baseMapper.selectDeptById(deptId);
    }

    @DataPermission(tableAlias = "d", deptColumn = "id")
    @Override
    public List<DeptVO> getDeptList(DeptQueryDTO deptQueryDTO) {
        return buildDeptTree(baseMapper.selectDeptList(deptQueryDTO));
    }


    @DataPermission(deptColumn = "id")
    @Override
    public void checkDataScope(List<Long> ids) {
        LambdaQueryWrapper<Dept> lqw = new LambdaQueryWrapper<>();
        lqw.in(Dept::getId, ids);

        long count = count(lqw);

        if (count != ids.size()) {
            throw new CustomException(ResultCodeEnum.NOT_DATA_SCOPE);
        }
    }

    /**
     * 构建部门树
     *
     * @param deptVOList 部门集合
     * @return 部门树
     */
    private List<DeptVO> buildDeptTree(List<DeptVO> deptVOList) {
        // 没有部门直接返回
        if (CollectionUtils.isEmpty(deptVOList)) {
            return new ArrayList<>();
        }

        // 创建Map便于查找
        Map<Long, DeptVO> menuMap = deptVOList.stream()
                .collect(Collectors.toMap(DeptVO::getId, deptVO -> deptVO));

        // 关联父子关系并找出根节点
        List<DeptVO> rootNodes = new ArrayList<>();

        for (DeptVO deptVO : deptVOList) {
            Long parentId = deptVO.getParentId();
            DeptVO parent = menuMap.get(parentId);

            if (parent != null) {
                // 有父节点，建立父子关系
                if (parent.getChildren() == null) {
                    parent.setChildren(new ArrayList<>());
                }
                parent.getChildren().add(deptVO);
            } else {
                // 没有父节点或父节点不在当前列表中，作为根节点
                rootNodes.add(deptVO);
            }
        }

        return rootNodes;
    }
}




